package com.luoying.itew.fragment;

import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Matrix;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.bigkoo.pickerview.TimePickerView;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.MarkerView;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.google.gson.Gson;
import com.luoying.itew.R;
import com.luoying.itew.activity.InformationActivity;
import com.luoying.itew.adapter.MyXFormatter;
import com.luoying.itew.bean.AngleRBean;
import com.luoying.itew.bean.DisplacementDirectionBean;
import com.luoying.itew.bean.DisplacementDirectionDayBean;
import com.luoying.itew.bean.DisplacementSpeedBean;
import com.luoying.itew.bean.MoniterRBean;
import com.luoying.itew.bean.MonitorBean;
import com.luoying.itew.common.AntaiApplication;
import com.luoying.itew.http.BaseMap;
import com.luoying.itew.http.HttpRequestUtils;
import com.luoying.itew.http.HttpResponseCallBack;
import com.luoying.itew.manage.LineChartManage;
import com.luoying.itew.manage.UserManage;
import com.luoying.itew.util.LogUtils;
import com.luoying.itew.util.ZXWUtils;
import com.luoying.itew.view.ButtonItemView;
import com.luoying.itew.view.ButtonItemViewTwo;
import com.luoying.itew.view.ChartsTypeItemView;
import com.luoying.itew.view.LineChartInViewPager;
import com.luoying.itew.view.MyMarkerView;
import com.luoying.itew.view.NewGridView;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by Administrator on 2018/5/24.
 * time 2018-5-10
 * author zm
 */
public class ChartsFragment extends BaseFragment implements ChartListener{
    private static final String TAG = "ChartsFragment";
    private static final String WEIYI ="位移";
    private static final String QINGJIAO ="倾角";
    private static final String SHUIWEI ="水位";
    private static final String SHENGDU ="深部位移";
    private static final String YULINAG ="雨量";
    private static final String ZHNEGDONG ="振动";
    @BindView(R.id.gv_charts_one)
    GridView gvChartsOne;
    Unbinder unbinder;
    @BindView(R.id.line_graphic_news)
    LineChartInViewPager lineChart;
    @BindView(R.id.gv_charts_two)
    GridView gvChartsTwo;
    @BindView(R.id.gv_charts_type)
    NewGridView gvChartsType;
    @BindView(R.id.tv_start_time)
    TextView tvStartTime;
    @BindView(R.id.rl_start_time)
    RelativeLayout rlStartTime;
    @BindView(R.id.tv_end_time)
    TextView tvEndTime;
    @BindView(R.id.rl_end_time)
    RelativeLayout rlEndTime;
    @BindView(R.id.rl_search)
    RelativeLayout rlSearch;
    @BindView(R.id.lr_chart_search)
    LinearLayout lrChartSearch;
    @BindView(R.id.tv_hour_chart)
    TextView tvHourChart;
    @BindView(R.id.tv_chart_fen)
    TextView tvChartFen;
    @BindView(R.id.tv_day_chart)
    TextView tvDayChart;
    @BindView(R.id.rl_chart_others)
    RelativeLayout rlChartOthers;
    @BindView(R.id.sp_type)
    Spinner spType;
    @BindView(R.id.rl_sp_type)
    RelativeLayout rlSpType;
    @BindView(R.id.sp_hole)
    Spinner holeSpinner;

    private TimePickerView startPickView;
    private TimePickerView endPickView;


    private String startTime;
    private String endTime;
    private MyAdapter adapterOne;
    private MoniterRBean bean;
    private MyTwoAdapter adapterTwo;
    private int chartBigType = 1;       // 1 位移 2 倾角 3 水位 4深部位移
    private int chartMiddelType = 1;   //1 位移走势 2 位移速度 3 位移加速度
    private int chartSmallType = 1;    //1 水平位移/水平速度/水平加速度 2 沉降位移/沉降速度/沉降加速度
    private int axis = 0;   //0 表示x轴  1 表示y轴   （int）
    private int angleType= 1;  //1 倾斜角变化量  2 倾斜率  3 温度  4 湿度  （String）
    private int waterType = 1 ;//1 水位时趋势图 (String)
    private int rainType = 1 ;//1 雨量时趋势图 (String)
    private int vibrationType = 1 ;//1 雨量时趋势图 (String)

    //深度位移时位移  1时趋势 4日趋势
    private int displacementType = 1;
    private ArrayList<Integer> colours;
    private List<String> legendDatas;
    private ChartTypeAdapter chartTypeAdapter;
    private List<String> categoryDatas;
    private int onClick; //0-big 1-middle 2 - small
    private ProgressDialog dialog;
    private DisplacementSpeedBean displacementSpeedBean;
    private int isFirstRefresh;
    private XAxis xAxis;
    private LineChartManage lineChartManage;
    private YAxis yAxis;
    private int dayOrHour = 0;  //0 - 时趋势图 1 - 日趋势图
    /**
     * 当前监测点对象
     */
    private MonitorBean monitorBean;
    /**
     * 当前选择的孔
     */
    private int tunnel =1;
    /**
     * 有无水位采集器
     */
    private boolean isWater =true;
    /**
     * 有无测斜仪
     */
    private boolean isInstrument =true;
    /**
     * 一级菜单选项
     */
    private List<String> list = new ArrayList<>();

    @Override
    protected int getLayoutResId() {
        return R.layout.charts_fragment;
    }


    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        LogUtils.e(TAG, "onViewCreated: ");
    }

    @Override
    protected void init() {
        super.init();
        monitorBean = UserManage.getInstance().getMonitorById(AntaiApplication.cuurMonitorId);
        initThings();
        initChart();
        loadDialog.show();
        sendRequest(-1);
        setGirdView();
        if(getActivity()!=null&&getActivity() instanceof InformationActivity){
            ((InformationActivity)getActivity()).setListenerList(this);
            gvChartsOne.post(new Runnable() {
                @Override
                public void run() {
                    ((InformationActivity)getActivity()).getMoitorDetail();
                }
            });
        }
    }

    private void initChart() {
        lineChartManage = new LineChartManage(lineChart);// no description text
        lineChart.getDescription().setEnabled(false);   //设置描述
        lineChart.setTouchEnabled(true);    //设置是否可以触摸
        lineChart.setDragDecelerationFrictionCoef(0.9f);    //设置滚动时的速度快慢
        lineChart.setDragEnabled(true);     // 是否可以拖拽
        lineChart.setScaleXEnabled(true);
        lineChart.setScaleYEnabled(false);
        lineChart.setScaleEnabled(false);    // 是否可以缩放 x和y轴, 默认是true
        lineChart.setDrawGridBackground(false);//设置图表内格子背景是否显示，默认是false
        lineChart.setHighlightPerDragEnabled(true);//能否拖拽高亮线(数据点与坐标的提示线)，默认是true
        lineChart.setBackgroundColor(Color.WHITE);  //设置背景颜色
        // 设置MarkerView
        MarkerView mv = new MyMarkerView(getContext(), R.layout.markview_chart);
        lineChart.setMarkerView(mv);
        xAxis = lineChart.getXAxis();

        xAxis.setLabelRotationAngle(25f);  //设置旋转偏移量
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        //设置标签文本格式
        xAxis.setTextSize(10f);
        //设置标签文本颜色
        xAxis.setTextColor(Color.rgb(255, 192, 56));
        //是否绘制轴线
        xAxis.setDrawAxisLine(true);
        //是否绘制网格线
        xAxis.setDrawGridLines(false);
        xAxis.setGranularity(1f);

        yAxis = lineChart.getAxisLeft();
        yAxis.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART);
        yAxis.setDrawGridLines(true);    //设置左边的网格线显示
        yAxis.setGranularityEnabled(false);//启用在放大时限制y轴间隔的粒度特性。默认值：false。
        yAxis.setTextColor(Color.rgb(255, 192, 56)); //设置Y轴文字颜色

        YAxis rightAxis = lineChart.getAxisRight(); //获取右边的Y轴
        rightAxis.setEnabled(false);   //设置右边的Y轴不显示


        //设置图例（也就是曲线的标签）
        Legend legend = lineChart.getLegend();//设置比例图
        //legend.setForm(Legend.LegendForm.NONE);
        //legend.setTextColor(Color.TRANSPARENT);
        legend.setEnabled(false);   //设置不显示比例图
    }

    private void showLoadDialog() {
        if (dialog == null) {
            dialog = new ProgressDialog(getContext());
        }
        dialog.setCanceledOnTouchOutside(false);
        dialog.setMessage("正在加载中");
        //
        dialog.show();
    }

    /**
     * 提前设置颜色集合
     */
    private void initThings() {
        //颜色集合
        colours = new ArrayList<>();
        colours.add(Color.parseColor("#0aba44"));
        colours.add(Color.BLUE);
        colours.add(Color.RED);
        colours.add(Color.CYAN);
        colours.add(Color.BLACK);
        colours.add(Color.GRAY);

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");// HH:mm:ss
        //获取当前时间
        startTime = "";
        endTime = "";//simpleDateFormat.format(date)
        LogUtils.d(TAG, "startTime == " + startTime + ",endTime == " + endTime);
    }

    /**
     * 传position是为了防止点击速度过快，导致请求到的数据和chartMiddelType参数不一致而产生的数据转换异常
     *
     * @param position -1代表默认值，不为-1代表请求返回的数据体发生更改
     */
    private void sendRequest(final int position) {
        BaseMap baseMap = new BaseMap()
                .put("chartBigType", chartBigType)
                .put("chartMiddelType", chartMiddelType)
                .put("chartSmallType",chartSmallType)
                .put("startDate",startTime)
                .put("endDate",endTime)
                .put("axis",axis)
                .put("angleType",angleType)
                .put("rainType",rainType)
                .put("vibrationType",vibrationType)
                .put("waterType",waterType);
        if(chartBigType==2&&dayOrHour==1){
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            if(!TextUtils.isEmpty(startTime)){
                try {
                    Date date = simpleDateFormat.parse(startTime);
                    startTime = sdf.format(date);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
            if(!TextUtils.isEmpty(endTime)){
                try {
                    Date date = simpleDateFormat.parse(endTime);
                    endTime = sdf.format(date);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }

        }
        baseMap.put("startDate",startTime)
                .put("endDate",endTime);
        LogUtils.d(TAG,baseMap.toString());
        HttpRequestUtils.getInstance().getCharts(String.valueOf(AntaiApplication.cuurMonitorId ), dayOrHour
                ,baseMap,new HttpResponseCallBack<Map>() {
                    @Override
                    public void onFail(String message) {
                        LogUtils.d(TAG, "onFail == " + message);
                        if (loadDialog != null) {
                            loadDialog.dismiss();
                        }
                    }

                    @Override
                    public void onSuccess(Map bean) {
                        if (loadDialog != null) {
                            loadDialog.dismiss();
                        }
                        String response = new Gson().toJson(bean);
                        if (chartBigType == 1){ //位移
                            if (position != -1) {
                                chartMiddelType = position;
                            }
                            LogUtils.d(TAG, "chartMiddelType == " + chartMiddelType);
                            try {
                                if (chartMiddelType == 1) {  //位移走势图表
                                    isFirstRefresh = 0;
                                    if (dayOrHour == 0) {  //时趋势图
                                        DisplacementDirectionBean displacementDirectionBean = new Gson().fromJson(response, DisplacementDirectionBean.class);
                                        setDisplacementDirectionData(displacementDirectionBean);
                                    } else {     //日趋势图
                                        DisplacementDirectionDayBean displacementDirectionDayBean = new Gson().fromJson(response, DisplacementDirectionDayBean.class);
                                        setDisplacementDirectionDayData(displacementDirectionDayBean);
                                    }
                                } else { //位移加速度图表
                                    displacementSpeedBean = new Gson().fromJson(response, DisplacementSpeedBean.class);
                                    setDisplacementSpeedData(displacementSpeedBean);
                                }
                            } catch (Exception e) {
                                LogUtils.d(TAG, e.toString());
                            }
                        }else if (chartBigType == 2 ||chartBigType == 5){   //倾角
                            AngleRBean angleRBean = new Gson().fromJson(response, AngleRBean.class);
                            try {
                                initAngleBean(angleRBean);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }else {     //水位
                            AngleRBean angleRBean = new Gson().fromJson(response, AngleRBean.class);
                            try {
                                initAngleBean(angleRBean);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }


                    }

                    @Override
                    public void onError(String message) {
                        LogUtils.d(TAG, "onError == " + message);
                        if (loadDialog != null) {
                            loadDialog.dismiss();
                        }
                    }
                });
    }


    /**
     * 设置倾角数据
     *
     * @param bean
     */
    private void initAngleBean(AngleRBean bean) throws Exception {
        //设置当前视图的偏移量（实际图表窗口的两侧偏移量）。 设置这个，将阻止图表自动计算它的偏移量。
        //lineChart.setViewPortOffsets(0f, 0f, 0f, 0f);
        Matrix m = new Matrix();
        m.postScale(1.5f, 1f);//两个参数分别是x,y轴的缩放比例。例如：将x轴的数据放大为之前的1.5倍
        lineChart.getViewPortHandler().refresh(m, lineChart, false);//将图表动画显示之前进行缩放
        lineChart.animateX(1000); // 立即执行的动画,x轴
        yAxis.setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                if (chartBigType == 2){ //倾角
                    if (angleType == 1){//1 倾斜角变化量  2 倾斜率  3 温度  4 湿度
                        return ZXWUtils.doubleToStringNo(value)+"°";
                    }else if (angleType == 2){   //温度保留一位小数
                        return ZXWUtils.doubleToStringNo(value);
                    }else if(angleType == 3){
                        return ZXWUtils.doubleToStringNo(value)+"°";
                    }else if(angleType == 4){
                        return ZXWUtils.doubleToStringNo(value)+"%";
                    }else {
                        return ZXWUtils.doubleToStringNo(value)+"mm";
                    }
                } else if (chartBigType == 3){   //水位
                    return ZXWUtils.doubleToStringNo(value)+"m";
                } else if (chartBigType == 4||chartBigType ==5){ //测斜仪
                    return ZXWUtils.doubleToStringNo(value)+"mm";
                } else if (chartBigType == 6){
                    return ZXWUtils.doubleToStringNo(value)+"g";
                }
                return ZXWUtils.doubleToString(value)+"";
            }
        });

        xAxis.setValueFormatter(new IAxisValueFormatter() { //设置筛选器
            SimpleDateFormat mFormat = new SimpleDateFormat(dayOrHour==0?"MM/dd HH:mm":"MM-dd",Locale.getDefault());
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                if(dayOrHour==0){
                    long millis = TimeUnit.HOURS.toMillis((long)value);
                    return mFormat.format(new Date((long)value));
                } else {
                    long millis = TimeUnit.DAYS.toMillis((long) value);
                    String xString = mFormat.format(new Date(millis));
                    return mFormat.format(new Date(millis));
                }
            }
        });

//        if(chartBigType==1){
//            xAxis.setAxisMaximum(20F);
//            xAxis.setAxisMinimum(-20F);
////            if(displacementType==2){
////                xAxis.setAxisMaximum(20F);
////                xAxis.setAxisMinimum(-20F);
////                xAxis.resetAxisMinimum();
////            } else {
////                xAxis.resetAxisMaximum();
////                xAxis.resetAxisMaximum();
////            }
//        } else {
//            xAxis.resetAxisMaximum();
//            xAxis.resetAxisMaximum();
//        }

        legendDatas = bean.getLegendDatas();
        List<AngleRBean.SeriesBean> series = bean.getSeries();
        int count =0;
        for (AngleRBean.SeriesBean seriesBean : series) {
            count = count+seriesBean.getData().size();
        }
        boolean noData = legendDatas==null||legendDatas.size()==0||series.size()==0||count==0;
        if (noData){
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    lineChart.setNoDataText("暂无数据");
                    lineChart.setNoDataTextColor(Color.BLACK);
                    lineChart.clear();
                    lineChart.invalidate();
                }
            },100);
            return;
        }

        SimpleDateFormat format;

        if(chartBigType==2 ||chartBigType ==6){
            if(dayOrHour==1){
                format = new SimpleDateFormat("yyyy/MM/dd",Locale.getDefault());
            } else {
                format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",Locale.getDefault());
            }
        }else {
            if(dayOrHour==1){
                format = new SimpleDateFormat("yyyy/MM/dd",Locale.getDefault());
            } else {
                format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss",Locale.getDefault());
            }
        }

        ArrayList<ILineDataSet> dataSets = new ArrayList<>();
        for (int i = 0; i < series.size(); ++i) {
            AngleRBean.SeriesBean seriesBean = series.get(i);
            String collectorName = seriesBean.getName();
            List<AngleRBean.SeriesBean.DataBean> data = seriesBean.getData();
            if (data == null || data.size() == 0) {
                break;
            }
            List<Entry> entries = new ArrayList<>(data.size());
            for (int j = 0; j < data.size(); ++j) {
                AngleRBean.SeriesBean.DataBean dataBean = data.get(j);   //第J条线
                String timestampStr = dataBean.getName();
                List<String> value = dataBean.getValue();
                if (!TextUtils.isEmpty(timestampStr)) {
                    double displacement = Double.valueOf(value.get(1));
                    long timestamp = format.parse(timestampStr).getTime();
                    if(chartBigType==4){
                        if(dayOrHour==1){
                            long days = TimeUnit.MILLISECONDS.toDays(timestamp);
                            entries.add(new Entry(days, (float) displacement));
                        } else {
                            entries.add(new Entry((float) timestamp, (float) displacement));
                        }
                    } else {
                        if(dayOrHour==1){
                             long days = TimeUnit.MILLISECONDS.toDays(timestamp);
                             entries.add(new Entry(days, (float) displacement));
                        } else {
                            float hour = TimeUnit.MILLISECONDS.toHours(timestamp);
//                            entries.add(new Entry(hour, (float) displacement));
                            entries.add(new Entry((float) timestamp, (float) displacement));
                        }
                    }
                }
            }
            LineDataSet lineDataSet = new LineDataSet(entries, collectorName);      //将第J条线的坐标点集合和名字传入构造

            lineChartManage.initLineDataSet(lineDataSet,  colours.get(i%colours.size()), false);    //将颜色集合设置进去，设置这条线对应的颜色值
            lineDataSet.setAxisDependency(YAxis.AxisDependency.LEFT);   //设置左右两边Y轴节点描述
            lineDataSet.setValueTextColor(ColorTemplate.getHoloBlue()); //设置节点文字颜色
            lineDataSet.setDrawCircles(false);  //设置是否显示节点的小圆点
            lineDataSet.setDrawValues(false);       //设置是否显示节点的值
            lineDataSet.setHighLightColor(Color.rgb(244, 117, 117));//当点击节点时，将会出现与节点水平和垂直的两条线，可以对其进行定制.此方法为设置线条颜色
            lineDataSet.setHighlightEnabled(true);//设置是否显示十字线
            dataSets.add(lineDataSet);
        }

        LineData data = new LineData(dataSets);     //将线条集合通过构造传入LineData中
        data.setValueTextColor(Color.BLUE);    //设置节点数据值的文本颜色
        data.setValueTextSize(9f);              //设置节点数据值的文字大小
        lineChart.setData(data);            //对象添加lineData数据
        refreshChartType();


    }

    /**
     * 位移的日趋势图
     * @param displacementDirectionDayBean
     */
    private void setDisplacementDirectionDayData(DisplacementDirectionDayBean displacementDirectionDayBean) {
        try {
            initDisplacementDirectionDayChart(displacementDirectionDayBean);
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(getContext(), "无法生成位移图", Toast.LENGTH_LONG).show();
        }
    }

    private void initDisplacementDirectionDayChart(DisplacementDirectionDayBean bean) throws ParseException {
        LogUtils.d(TAG, "日趋势图表开始绘制");
        //lineChart.setViewPortOffsets(0f, 0f, 0f, 0f);   //设置当前视图的偏移量（实际图表窗口的两侧偏移量）。 设置这个，将阻止图表自动计算它的偏移量。
        Matrix m = new Matrix();
        m.postScale(1.5f, 1f);//两个参数分别是x,y轴的缩放比例。例如：将x轴的数据放大为之前的1.5倍
        lineChart.getViewPortHandler().refresh(m, lineChart, false);//将图表动画显示之前进行缩放

        lineChart.animateX(1000); // 立即执行的动画,x轴
        yAxis.setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                return ZXWUtils.doubleToString(value) + " mm";
            }
        });
        xAxis.setValueFormatter(new IAxisValueFormatter() { //设置筛选器

            private SimpleDateFormat mFormat = new SimpleDateFormat("MM-dd");

            @Override
            public String getFormattedValue(float value, AxisBase axis) {

                long millis = TimeUnit.DAYS.toMillis((long) value);
                //LogUtils.d(TAG,"X == " + mFormat.format(new Date(millis)));
                return mFormat.format(new Date(millis));
            }
        });

        legendDatas = bean.getLegendDatas();
        List<DisplacementDirectionDayBean.SeriesBean> series = bean.getSeries();
        int count =0;
        for (DisplacementDirectionDayBean.SeriesBean seriesBean : series) {
            count = count+seriesBean.getData().size();
        }
        boolean noData = legendDatas==null||legendDatas.size()==0||series.size()==0||count==0;
        if (noData){
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    lineChart.setNoDataText("暂无数据");
                    lineChart.setNoDataTextColor(Color.BLACK);
//                    mChart.setDescription(null);
                    lineChart.clear();
                    lineChart.invalidate();
//                    mChart.refreshDrawableState();
                }
            },100);
            return;
        }

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

        ArrayList<ILineDataSet> dataSets = new ArrayList<>();
        for (int i = 0; i < series.size(); ++i) {
            DisplacementDirectionDayBean.SeriesBean seriesBean = series.get(i);
            String collectorName = seriesBean.getName();
            List<DisplacementDirectionDayBean.SeriesBean.DataBean> data = seriesBean.getData();
            if (data == null || data.size() == 0) {
                break;
            }
            List<Entry> entries = new ArrayList<>(data.size());
            for (int j = 0; j < data.size(); ++j) {
                DisplacementDirectionDayBean.SeriesBean.DataBean dataBean = data.get(j);   //第J条线

                String timestampStr = dataBean.getName();
                List<String> value = dataBean.getValue();
                if (!TextUtils.isEmpty(timestampStr)) {
                    double displacement = Double.valueOf(value.get(1));
                    long timestamp = format.parse(timestampStr).getTime();
                    long days = TimeUnit.MILLISECONDS.toDays(timestamp);
                    //float hour = TimeUnit.MILLISECONDS.toHours(timestamp);
                    entries.add(new Entry(days, (float) displacement));     //第J条线的坐标点
                }

            }
            LineDataSet lineDataSet = new LineDataSet(entries, collectorName);      //将第J条线的坐标点集合和名字传入构造

            lineChartManage.initLineDataSet(lineDataSet,  colours.get(i%colours.size()), false);    //将颜色集合设置进去，设置这条线对应的颜色值
            lineDataSet.setAxisDependency(YAxis.AxisDependency.LEFT);   //设置左右两边Y轴节点描述
            lineDataSet.setValueTextColor(ColorTemplate.getHoloBlue()); //设置节点文字颜色
            lineDataSet.setDrawCircles(false);  //设置是否显示节点的小圆点
            lineDataSet.setDrawValues(false);       //设置是否显示节点的值
            lineDataSet.setHighLightColor(Color.rgb(244, 117, 117));//当点击节点时，将会出现与节点水平和垂直的两条线，可以对其进行定制.此方法为设置线条颜色
            lineDataSet.setHighlightEnabled(true);//设置是否显示十字线
            dataSets.add(lineDataSet);
        }

        LineData data = new LineData(dataSets);     //将线条集合通过构造传入LineData中
        data.setValueTextColor(Color.BLUE);    //设置节点数据值的文本颜色
        data.setValueTextSize(9f);              //设置节点数据值的文字大小
        lineChart.setData(data);            //对象添加lineData数据
        refreshChartType();
    }

    /**
     * 位移时趋势图
     * @param displacementDirectionBean
     */
    private void setDisplacementDirectionData(DisplacementDirectionBean displacementDirectionBean) {
        try {
            initDisplacementDirectionChart(displacementDirectionBean);
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(getContext(), "无法生成位移图", Toast.LENGTH_LONG).show();
        }
    }

    /**
     * 位移加速度
     *
     * @param displacementSpeedBean
     */
    private void setDisplacementSpeedData(DisplacementSpeedBean displacementSpeedBean) {
        try {
            initDisplacementSpeedChart(displacementSpeedBean);
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(getContext(), "无法生成位移图", Toast.LENGTH_LONG).show();
        }
    }

    /**
     * 设置位移速度图表的属性
     *
     * @param displacementSpeedBean
     */
    private void initDisplacementSpeedChart(DisplacementSpeedBean displacementSpeedBean) {
        categoryDatas = displacementSpeedBean.getCategoryDatas();
        legendDatas = displacementSpeedBean.getLegendDatas();
        Matrix m = new Matrix();
        m.postScale(1.5f, 1f);//两个参数分别是x,y轴的缩放比例。例如：将x轴的数据放大为之前的1.5倍
        lineChart.getViewPortHandler().refresh(m, lineChart, false);//将图表动画显示之前进行缩放

        lineChart.animateX(1000); // 立即执行的动画,x轴

        LogUtils.d(TAG, "SIZE == " + categoryDatas.size());
        MyXFormatter formatter = new MyXFormatter(categoryDatas);
        xAxis.setValueFormatter(formatter);
        yAxis.setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                if (chartMiddelType == 2) {//位移速度
                    return ZXWUtils.doubleToString(value) + " mm/周";
                } else {
                    return ZXWUtils.doubleToString(value) + " mm/周²";
                }
            }
        });

        List<DisplacementSpeedBean.SeriesBean> series = displacementSpeedBean.getSeries();
        int count =0;
        for (DisplacementSpeedBean.SeriesBean seriesBean : series) {
            count = count+seriesBean.getData().size();
        }
        boolean noData = legendDatas==null||legendDatas.size()==0||series.size()==0||count==0;
        if (noData){
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    lineChart.setNoDataText("暂无数据");
                    lineChart.setNoDataTextColor(Color.BLACK);
//                    mChart.setDescription(null);
                    lineChart.clear();
                    lineChart.invalidate();
//                    mChart.refreshDrawableState();
                }
            },100);
            return;
        }

        ArrayList<ILineDataSet> dataSets = new ArrayList<>();
        for (int i = 0; i < series.size(); ++i) {
            DisplacementSpeedBean.SeriesBean seriesBean = series.get(i);
            String collectorName = seriesBean.getName();
            List<DisplacementSpeedBean.SeriesBean.DataBean> data = seriesBean.getData();
            if (data == null || data.size() == 0) {
                break;
            }
            List<Entry> entries = new ArrayList<>(data.size());
            for (int j = 0; j < data.size(); ++j) {

                String aDouble = data.get(j).getValue();
                if (!TextUtils.isEmpty(aDouble)) {
                    entries.add(new Entry(j, Float.valueOf(aDouble)));
                }
            }
            LineDataSet lineDataSet = new LineDataSet(entries, collectorName);      //将第J条线的坐标点集合和名字传入构造

            lineChartManage.initLineDataSet(lineDataSet,  colours.get(i%colours.size()), false);    //将颜色集合设置进去，设置这条线对应的颜色值
            lineDataSet.setAxisDependency(YAxis.AxisDependency.LEFT);   //设置左右两边Y轴节点描述
            lineDataSet.setValueTextColor(ColorTemplate.getHoloBlue()); //设置节点文字颜色
            lineDataSet.setDrawCircles(false);  //设置是否显示节点的小圆点
            lineDataSet.setDrawValues(false);       //设置是否显示节点的值
            lineDataSet.setHighLightColor(Color.rgb(244, 117, 117));//当点击节点时，将会出现与节点水平和垂直的两条线，可以对其进行定制.此方法为设置线条颜色
            lineDataSet.setHighlightEnabled(true);//设置是否显示十字线
            dataSets.add(lineDataSet);
        }
        LineData data = new LineData(dataSets);
        lineChart.setData(data);
        data.setValueTextColor(Color.WHITE);    //设置节点数据值的文本颜色
        data.setValueTextSize(9f);              //设置节点数据值的文字大小
        ++isFirstRefresh;
        if (isFirstRefresh == 1) {   //当数据格式发生改变，此图表就刷新两遍，防止x轴显示不全
            lineChart.setData(data);

        }
        refreshChartType();


    }

    /**
     * 自定义比例图
     */
    private void refreshChartType() {
        chartTypeAdapter = new ChartTypeAdapter(getContext());
        gvChartsType.setAdapter(chartTypeAdapter);
        chartTypeAdapter.notifyDataSetChanged();

    }

    @OnClick({R.id.rl_chart_others, R.id.rl_start_time, R.id.rl_end_time, R.id.rl_search})
    public void onViewClicked(View view) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd",Locale.getDefault());// HH:mm:ss
        switch (view.getId()) {
            case R.id.rl_chart_others:  //日趋势图/时趋势图
                loadDialog.show();
                if (dayOrHour != 1) { //时趋势图
                    dayOrHour = 1;
                    //获取当前时间
                    Date date = new Date(System.currentTimeMillis());
                    long currentTimeMills = date.getTime();
                    long startTimeDays = TimeUnit.MILLISECONDS.toDays(currentTimeMills) - 30;
                    long startTimeMillis = TimeUnit.DAYS.toMillis(startTimeDays);
                    String startDate = simpleDateFormat.format(new Date(startTimeMillis));
                    startTime = startDate;
                    endTime = simpleDateFormat.format(currentTimeMills);
                      //时趋势图 -->  日趋势图++
                    tvStartTime.setText("开始时间");
                    tvEndTime.setText("结束时间");
                    rlEndTime.setVisibility(View.VISIBLE);
                    tvDayChart.setTextSize(16);
                    tvDayChart.setTextColor(getResources().getColor(R.color.blue));
                    tvHourChart.setTextSize(14);
                    tvHourChart.setTextColor(getResources().getColor(R.color.gray));
                    if(chartBigType==4){
                        getInclinometerChat();
                    } else {
                        sendRequest(-1);
                    }
                } else { //时趋势图
                    dayOrHour = 0;
                    startTime=simpleDateFormat.format(new Date());
                    endTime = "";
                    tvStartTime.setText("开始时间");
                    rlEndTime.setVisibility(View.GONE);
                    tvDayChart.setTextSize(14);
                    tvDayChart.setTextColor(getResources().getColor(R.color.gray));
                    tvHourChart.setTextSize(16);
                    tvHourChart.setTextColor(getResources().getColor(R.color.blue));
                    if(chartBigType==4){
                        getInclinometerChat();
                    } else {
                        sendRequest(-1);
                    }
                }
                break;
            case R.id.rl_start_time:    //开始时间
                showStartDateDialog();
                break;
            case R.id.rl_end_time:      //结束时间
                showEndDateDialog();
                break;
            case R.id.rl_search:        //查找
                loadDialog.show();
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                long startTimes = 0;
                long endTimes = 0;
                try {
                    startTimes = format.parse(startTime).getTime();
                    endTimes = format.parse(endTime).getTime();

                } catch (ParseException e) {
                    e.printStackTrace();

                }
                float startDays = TimeUnit.MILLISECONDS.toDays(startTimes);
                float endDays = TimeUnit.MILLISECONDS.toDays(endTimes);
                float values = endDays - startDays;
                LogUtils.d(TAG, "时间差 == " + values);
                if (values > 180) {
                    loadDialog.dismiss();
                    Toast.makeText(getActivity(), "请将时间差控制在半年内", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (values <= 0 && endDays != 0) {
                    loadDialog.dismiss();
                    Toast.makeText(getActivity(), "时间格式错误", Toast.LENGTH_SHORT).show();
                    return;
                }
                if(chartBigType==4){
                    getInclinometerChat();
                } else {
                    sendRequest(-1);
                }

                break;
        }
    }

    private void showEndDateDialog() {
        Calendar selectedDate = Calendar.getInstance();
        Calendar startDate = Calendar.getInstance();
        //startDate.set(2013,1,1);
        Calendar endDate = Calendar.getInstance();
        //endDate.set(2020,1,1);
        int mYear = endDate.get(Calendar.YEAR);
        int month = endDate.get(Calendar.DAY_OF_MONTH);
        int date = endDate.get(Calendar.DATE);
        startDate.set(2018, 0, 1);
//        endDate.set(2020,11,31);
        selectedDate.set(mYear, month, date);
        endPickView = new TimePickerView.Builder(getActivity(), new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
                String tempBirthday = df.format(date);
                LogUtils.d(TAG, "startTime Select == " + tempBirthday + "23:59:59");
                endTime = tempBirthday;
                tvEndTime.setText(tempBirthday);
            }
        })
                .setType(new boolean[]{true, true, true, false, false, false})// 默认全部显示
                .setCancelText("取消")//取消按钮文字
                .setSubmitText("确定")//确认按钮文字
                .setContentSize(18)//滚轮文字大小
                .setTextColorOut(Color.BLACK)
                .setTextColorCenter(0xFF333333)
                .setTitleSize(20)//标题文字大小
                .setTitleText("日期选择")//标题文字
                .setTitleColor(Color.BLACK)//标题文字颜色
                .setSubmitColor(0xFF888888)//确定按钮文字颜色
                .setCancelColor(0xFF888888)//取消按钮文字颜色
                .setTitleBgColor(0xFFeeeeee)//标题背景颜色 Night mode
                .setBgColor(0xFFffffff)//滚轮背景颜色 Night mode
                .isCyclic(false)//是否循环滚动
                .setDate(selectedDate)// 如果不设置的话，默认是系统时间*/
                .setRangDate(startDate, endDate)//起始终止年月日设定
                .setLabel("年", "月", "日", "时", "分", "秒")//默认设置为年月日时分秒
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .isDialog(false)//是否显示为对话框样式
                .build();
        endPickView.show();
    }

    private void showStartDateDialog() {
        Calendar selectedDate = Calendar.getInstance();
        Calendar startDate = Calendar.getInstance();
        //startDate.set(2013,1,1);
        Calendar endDate = Calendar.getInstance();
        //endDate.set(2020,1,1);
        //正确设置方式 原因：注意事项有说明
        // mYear = .get(Calendar.YEAR); // 获取当前年份
        int mYear = endDate.get(Calendar.YEAR);
        int month = endDate.get(Calendar.DAY_OF_MONTH);
        int date = endDate.get(Calendar.DATE);
        startDate.set(2018, 0, 1);
//        endDate.set(2020,11,31);
        selectedDate.set(mYear, month, date);
        startPickView = new TimePickerView.Builder(getActivity(), new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
                String tempBirthday = df.format(date);
                LogUtils.d(TAG, "startTime Select == " + tempBirthday);
                startTime = tempBirthday;
                tvStartTime.setText(tempBirthday);
            }
        })
                .setType(new boolean[]{true, true, true, false, false, false})// 默认全部显示
                .setCancelText("取消")//取消按钮文字
                .setSubmitText("确定")//确认按钮文字
                .setContentSize(18)//滚轮文字大小
                .setTextColorOut(Color.BLACK)
                .setTextColorCenter(0xFF333333)
                .setTitleSize(20)//标题文字大小
                .setTitleText("日期选择")//标题文字
                .setTitleColor(Color.BLACK)//标题文字颜色
                .setSubmitColor(0xFF888888)//确定按钮文字颜色
                .setCancelColor(0xFF888888)//取消按钮文字颜色
                .setTitleBgColor(0xFFeeeeee)//标题背景颜色 Night mode
                .setBgColor(0xFFffffff)//滚轮背景颜色 Night mode
                .isCyclic(false)//是否循环滚动
                .setDate(selectedDate)// 如果不设置的话，默认是系统时间*/
                .setRangDate(startDate, endDate)//起始终止年月日设定
                .setLabel("年", "月", "日", "时", "分", "秒")//默认设置为年月日时分秒
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .isDialog(false)//是否显示为对话框样式
                .build();
        startPickView.show();
    }

    @Override
    public void onDataUpdate() {
        if(getActivity()==null)
            return;
        isWater = ((InformationActivity)getActivity()).isWaterCollector();
        isInstrument = ((InformationActivity)getActivity()).isInstrument();
        list.clear();
        list.add(WEIYI);
        list.add(QINGJIAO);
        if(isWater){
            list.add(SHUIWEI);
        }
        if(isInstrument){
            list.add(SHENGDU);
        }
        if(((InformationActivity)getActivity()).isYuCollector()){
            list.add(YULINAG);
        }
        if(((InformationActivity)getActivity()).isZhengCollector()){
            list.add(ZHNEGDONG);
        }


        adapterOne.notifyDataSetChanged();

    }


    class ChartTypeAdapter extends BaseAdapter {
        int mposition;
        //上下文对象
        private Context context;


        ChartTypeAdapter(Context context) {
            this.context = context;
        }

        @Override
        public int getCount() {
            if (legendDatas!=null){
                return legendDatas.size();
            }else {
                return 0;
            }
        }

        @Override
        public Object getItem(int position) {
            return position;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, final View convertView, ViewGroup parent) {
            mposition = position;

            final ChartsTypeItemView button;
            if (convertView == null) {

                button = new ChartsTypeItemView(context);

            } else {
                button = (ChartsTypeItemView) convertView;
            }

            button.setText(legendDatas.get(position%legendDatas.size()), colours.get(position%colours.size()));//为ImageView设置图片资源
            return button;

        }
    }

    /**
     * 设置位移走势图表的具体属性
     *
     * @param bean
     */
    private void initDisplacementDirectionChart(DisplacementDirectionBean bean) throws Exception {

        //lineChart.setViewPortOffsets(0f, 0f, 0f, 0f);   //设置当前视图的偏移量（实际图表窗口的两侧偏移量）。 设置这个，将阻止图表自动计算它的偏移量。
        Matrix m = new Matrix();
        m.postScale(1.5f, 1f);//两个参数分别是x,y轴的缩放比例。例如：将x轴的数据放大为之前的1.5倍
        lineChart.getViewPortHandler().refresh(m, lineChart, false);//将图表动画显示之前进行缩放

        lineChart.animateX(1000); // 立即执行的动画,x轴

        yAxis = new YAxis();
        yAxis = lineChart.getAxisLeft();
        yAxis.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART);
        yAxis.setDrawGridLines(true);    //设置左边的网格线显示
        yAxis.setGranularityEnabled(false);//启用在放大时限制y轴间隔的粒度特性。默认值：false。
        yAxis.setTextColor(Color.rgb(255, 192, 56)); //设置Y轴文字颜色

        yAxis.setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                return ZXWUtils.doubleToStringNo(value) + " mm";
            }
        });
        xAxis.setValueFormatter(new IAxisValueFormatter() { //设置筛选器

            private SimpleDateFormat mFormat = new SimpleDateFormat("MM/dd HH:mm");

            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                long millis = TimeUnit.HOURS.toMillis((long)value);
                return mFormat.format(new Date(millis));
            }
        });

        if(chartBigType==1&&dayOrHour==0){
            yAxis.setAxisMaximum(30F);
            yAxis.setAxisMinimum(-20F);
//            if(displacementType==2){
//                xAxis.setAxisMaximum(20F);
//                xAxis.setAxisMinimum(-20F);
//                xAxis.resetAxisMinimum();
//            } else {
//                xAxis.resetAxisMaximum();
//                xAxis.resetAxisMaximum();
//            }
        } else {
            yAxis.setGranularityEnabled(true);
            yAxis.setAxisMaximum(0);
            yAxis.resetAxisMaximum();
            yAxis.setAxisMinimum(0);
            yAxis.resetAxisMinimum();
        }


        legendDatas = bean.getLegendDatas();
        List<DisplacementDirectionBean.SeriesBean> series = bean.getSeries();
        int count =0;
        for (DisplacementDirectionBean.SeriesBean seriesBean : series) {
            count = count+seriesBean.getData().size();
        }
        boolean noData = legendDatas.size()==0||series.size()==0||count==0;
        if (noData){
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    lineChart.setNoDataText("暂无数据");
                    lineChart.setNoDataTextColor(Color.BLACK);
//                    mChart.setDescription(null);
                    lineChart.clear();
                    lineChart.invalidate();
//                    mChart.refreshDrawableState();
                }
            },100);
            return;
        }


        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        ArrayList<ILineDataSet> dataSets = new ArrayList<>();
        for (int i = 0; i < series.size(); ++i) {
            DisplacementDirectionBean.SeriesBean seriesBean = series.get(i);
            String collectorName = seriesBean.getName();
            List<DisplacementDirectionBean.SeriesBean.DataBean> data = seriesBean.getData();
            if (data == null || data.size() == 0) {
                break;
            }
            List<Entry> entries = new ArrayList<>(data.size());
            for (int j = 0; j < data.size(); ++j) {
                DisplacementDirectionBean.SeriesBean.DataBean dataBean = data.get(j);   //第J条线

                String timestampStr = dataBean.getName();
                List<String> value = dataBean.getValue();
                if (!TextUtils.isEmpty(timestampStr)) {
//                    double displacement = Double.valueOf(value.get(1));
//                    long timestamp = format.parse(timestampStr).getTime();
//                    float hour = TimeUnit.MILLISECONDS.toHours(timestamp);
//                    Entry entry = new Entry(hour,(float) displacement);
//                    entries.add(entry);     //第J条线的坐标点
                    double displacement = Double.valueOf(value.get(1));
                    long timestamp = format.parse(timestampStr).getTime();
                    float hour = TimeUnit.MILLISECONDS.toHours(timestamp);
                    entries.add(new Entry(hour, (float) displacement));     //第J条线的坐标点
                }

            }
            LineDataSet lineDataSet = new LineDataSet(entries, collectorName);      //将第J条线的坐标点集合和名字传入构造

            lineChartManage.initLineDataSet(lineDataSet, colours.get(i%colours.size()), false);    //将颜色集合设置进去，设置这条线对应的颜色值
            lineDataSet.setAxisDependency(YAxis.AxisDependency.LEFT);   //设置左右两边Y轴节点描述
            lineDataSet.setValueTextColor(ColorTemplate.getHoloBlue()); //设置节点文字颜色
            lineDataSet.setDrawCircles(false);  //设置是否显示节点的小圆点
            lineDataSet.setDrawValues(false);       //设置是否显示节点的值
            lineDataSet.setHighLightColor(Color.rgb(244, 117, 117));//当点击节点时，将会出现与节点水平和垂直的两条线，可以对其进行定制.此方法为设置线条颜色
            lineDataSet.setHighlightEnabled(true);//设置是否显示十字线
            dataSets.add(lineDataSet);
        }

        LineData data = new LineData(dataSets);     //将线条集合通过构造传入LineData中
        data.setValueTextColor(Color.BLUE);    //设置节点数据值的文本颜色
        data.setValueTextSize(9f);              //设置节点数据值的文字大小
        lineChart.setData(data);            //对象添加lineData数据
        refreshChartType();

    }

    /**
     * 设置GirdView 对象
     */
    private void setGirdView() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd",Locale.getDefault());
        Date curDate =  new Date(System.currentTimeMillis());
        startTime  =  formatter.format(curDate);
        ArrayAdapter<CharSequence> arrayAdapter = ArrayAdapter.createFromResource(getContext(),
                R.array.xyType,android.R.layout.simple_list_item_1);
        spType.setAdapter(arrayAdapter);
        spType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                LogUtils.d(TAG, ",XY position == " + position);
                axis = position;
                if(chartBigType==4){
                    getInclinometerChat();
                } else {
                    sendRequest(-1);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        //设置采斜仪孔集合
        if(monitorBean.getTunnels()>0){
            String[] arrays = new String[monitorBean.getTunnels()];
            for (int i = 0; i <monitorBean.getTunnels() ; i++) {
                arrays[i] = (i+1)+ "号孔";
            }
            ArrayAdapter<String> adapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_item, arrays);
            //设置下拉列表框的下拉选项样式
            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            holeSpinner.setAdapter(adapter);
            holeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                    tunnel = i+1;
                    sendRequest(-1);
                }

                @Override
                public void onNothingSelected(AdapterView<?> adapterView) {

                }
            });
        }
//        list.add("位移");
//        list.add("倾角");
//        if(isWater){
//            list.add("水位");
//        }
//        if(isInstrument){
//            list.add("深度位移");
//        }

        adapterOne = new MyAdapter(getContext(),list);
        gvChartsOne.setAdapter(adapterOne);
        gvChartsOne.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                loadDialog.show();
                //单选效果
                select = position;
                //这里避免错位
//                if(isInstrument&&!isWater){
//                    position = position+1;
//                }
                String menuStr = list.get(position);
                if(menuStr.equals(WEIYI)){
                    chartBigType =1;
                    selectType2 = new String[]{"水平位移", "沉降位移"};
                    lrChartSearch.setVisibility(View.VISIBLE);
                    rlSpType.setVisibility(View.VISIBLE);
                    gvChartsTwo.setVisibility(View.VISIBLE);
                    rlChartOthers.setVisibility(View.VISIBLE);
                    holeSpinner.setVisibility(View.GONE);
                }
                if(menuStr.equals(QINGJIAO)){
                    chartBigType =2;
                    selectType2 = new String[]{"倾斜角变化量"};
                    rlSpType.setVisibility(View.VISIBLE);
                    gvChartsTwo.setVisibility(View.GONE);
                    rlChartOthers.setVisibility(View.VISIBLE);
                    lrChartSearch.setVisibility(View.VISIBLE);
                    holeSpinner.setVisibility(View.GONE);
                }
                if(menuStr.equals(SHUIWEI)){
                    chartBigType =3;
                    selectType2 = new String[]{"水位时趋势图"};
                    rlSpType.setVisibility(View.INVISIBLE);
                     gvChartsTwo.setVisibility(View.GONE);
                    rlChartOthers.setVisibility(View.GONE);
                    lrChartSearch.setVisibility(View.VISIBLE);
                    rlEndTime.setVisibility(View.GONE);
                    holeSpinner.setVisibility(View.GONE);
                }

                if(menuStr.equals(SHENGDU)){
                    chartBigType =4;
                    selectType2 = new String[]{"时位移"};
                    rlSpType.setVisibility(View.VISIBLE);
                    gvChartsTwo.setVisibility(View.VISIBLE);
                    rlChartOthers.setVisibility(View.VISIBLE);
                    lrChartSearch.setVisibility(View.VISIBLE);
                    rlEndTime.setVisibility(View.VISIBLE);
                    if(monitorBean.getTunnels()>0){
                        holeSpinner.setVisibility(View.VISIBLE);
                    } else {
                        holeSpinner.setVisibility(View.GONE);
                    }
                }

                if(menuStr.equals(YULINAG)){
                    chartBigType =5;
                    rainType = 1;
                    dayOrHour = 0;
                    selectType2 = new String[]{"雨量时趋势图"};
                    rlSpType.setVisibility(View.INVISIBLE);
                    gvChartsTwo.setVisibility(View.GONE);
                    rlChartOthers.setVisibility(View.GONE);
                    lrChartSearch.setVisibility(View.VISIBLE);
                    rlEndTime.setVisibility(View.GONE);
                    holeSpinner.setVisibility(View.GONE);
                }

                if(menuStr.equals(ZHNEGDONG)){
                    chartBigType =6;
                    vibrationType =1;
                    dayOrHour = 0;
                    selectType2 = new String[]{"震动时趋势图"};
                    rlSpType.setVisibility(View.VISIBLE);
                    gvChartsTwo.setVisibility(View.GONE);
                    rlChartOthers.setVisibility(View.GONE);
                    lrChartSearch.setVisibility(View.VISIBLE);
                    rlEndTime.setVisibility(View.GONE);
                    holeSpinner.setVisibility(View.GONE);
                }

                ArrayAdapter<CharSequence> arrayAdapter;
                if(chartBigType == 6){
                    arrayAdapter = ArrayAdapter.createFromResource(getContext(),
                            R.array.xyzType,android.R.layout.simple_list_item_1);
                } else {
                    arrayAdapter = ArrayAdapter.createFromResource(getContext(),
                            R.array.xyType,android.R.layout.simple_list_item_1);
                }
                spType.setAdapter(arrayAdapter);

                selectTwo = 0;
                resetChat();
                adapterOne.notifyDataSetChanged();
                adapterTwo.notifyDataSetChanged();
                // TODO
                if(chartBigType==4){
                    getInclinometerChat();
                } else {
                    sendRequest(-1);
                }
            }
        });

        adapterTwo = new MyTwoAdapter(getContext());
        gvChartsTwo.setAdapter(adapterTwo);
        gvChartsTwo.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //showLoadDialog();
                loadDialog.show();
                selectTwo = position;
                LogUtils.d(TAG, selectType2[position]);
                adapterTwo.notifyDataSetChanged();
                if(position==0){
                    chartSmallType =1;
                } else {
                    chartSmallType =2;
                }
                if(chartBigType==4){
                    lrChartSearch.setVisibility(View.VISIBLE);
                    rlChartOthers.setVisibility(View.VISIBLE);
                    getInclinometerChat();
                } else {
                    sendRequest(-1);
                }
            }
        });
    }

    /**
     * 重置设置图表选项
     */

    public void  resetChat(){
        //xy轴
        spType.setSelection(0,true);
        axis = 0;

        //开始时间
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd",Locale.getDefault());
        startTime =  formatter.format(new Date());
        tvStartTime.setText("开始时间");
        rlEndTime.setVisibility(View.GONE);

        //时趋势
        dayOrHour = 0;
        tvStartTime.setText("开始时间");
        rlEndTime.setVisibility(View.GONE);
        tvDayChart.setTextSize(14);
        tvDayChart.setTextColor(getResources().getColor(R.color.gray));
        tvHourChart.setTextSize(16);
        tvHourChart.setTextColor(getResources().getColor(R.color.blue));
        endTime = "";
        

    }

    /**
     * 测斜仪接口
     */
    public void getInclinometerChat(){
        if(dayOrHour==0){
            displacementType =1;
        } else {
            displacementType =4;
        }
        BaseMap baseMap = new BaseMap()
                .put("monitorPointId",String.valueOf(AntaiApplication.cuurMonitorId ))
                .put("displacementType", displacementType)
                .put("date", startTime)
                .put("startDate",startTime)
                .put("endDate",endTime)
                .put("tunnel", tunnel)
                .put("axis",axis);
        LogUtils.e(new Gson().toJson(baseMap));
        HttpRequestUtils.getInstance().getInclinometerChat(baseMap, new HttpResponseCallBack<Map>() {
            @Override
            public void onFail(String message) {
                loadDialog.dismiss();
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        lineChart.setNoDataText("暂无数据");
                        lineChart.setNoDataTextColor(Color.BLACK);
                        lineChart.clear();
                        lineChart.invalidate();
                    }
                },100);
            }

            @Override
            public void onSuccess(Map data) {
                loadDialog.dismiss();
                String response = new Gson().toJson(data);
                //日趋势
                AngleRBean angleRBean = new Gson().fromJson(response, AngleRBean.class);
                try {
                    initAngleBean(angleRBean);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onError(String message) {
                loadDialog.dismiss();
            }
        });
    }



    private String[] selectType2 = {
            "水平位移", "沉降位移"
    };
    int select;

    class MyAdapter extends BaseAdapter {
        int mposition;
        //上下文对象
        private Context context;
        private List<String> listTitle;


        MyAdapter(Context context,List<String> listTitle) {
            this.context = context;
            this.listTitle = listTitle;
        }

        @Override
        public int getCount() {
            return listTitle.size();
        }

        @Override
        public Object getItem(int position) {
            return position;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, final View convertView, ViewGroup parent) {
            mposition = position;

            final ButtonItemView button;
            if (convertView == null) {

                button = new ButtonItemView(context);

            } else {
                button = (ButtonItemView) convertView;
            }
            if (select == position) {
                button.setSelect();
            } else {
                button.setNormal();
            }
            button.setText(listTitle.get(position));//为ImageView设置图片资源
            return button;

        }
    }

    private int selectTwo;

    class MyTwoAdapter extends BaseAdapter {
        int mposition;
        //上下文对象
        private Context context;


        MyTwoAdapter(Context context) {
            this.context = context;
        }

        @Override
        public int getCount() {
            return selectType2.length;
        }

        @Override
        public Object getItem(int position) {
            return position;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, final View convertView, ViewGroup parent) {
            mposition = position;

            final ButtonItemViewTwo button;
            if (convertView == null) {

                button = new ButtonItemViewTwo(context);

            } else {
                button = (ButtonItemViewTwo) convertView;
            }
            if (selectTwo == position) {
                button.setSelect();
            } else {
                button.setNormal();
            }
            button.setText(selectType2[position]);//为ImageView设置图片资源
            return button;

        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if(getActivity()!=null){
            ((InformationActivity)getActivity()).removeListener(this);
        }
        unbinder.unbind();
    }

}
